Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

10.2 Allocating a Private Memory Block for Each Core

10.2.1 Private Memory Allocation Strategy

Because the Linux operating system utilizes page translation tables to execute transformations between virtual addresses and physical addresses, it must continuously access these page tables throughout its operation. To enhance memory access efficiency, Linux typically establishes a fundamental minimum unit when allocating memory, rather than performing memory allocation on a raw byte granularity. The choice of this minimum unit directly dictates the overall efficiency of memory utilization. This minimum unit is generally a page.

The private memory for each individual CPU primarily comprises the static memory blocks generated by the compiler and linker, situated between the symbols __per_cpu_start and __per_cpu_end. Combined with the reserved memory blocks designated for loadable modules and a dedicated portion allocated for dynamic runtime usage, these three components are collectively referred to as the minimum required allocation memory. Because memory allocation constraints enforce a minimum allocation unit size (atom_size), the actual allocated memory space must evaluate to an integer multiple of this atomic size. Consequently, the actual magnitude of allocated memory (alloc_size) is generally larger than the baseline minimum required allocation memory.

For uniprocessor (UP) systems, memory utilization efficiency can reach its theoretical maximum when memory is partitioned using this minimum allocation unit. Conversely, for systems featuring a Non-Uniform Memory Access (NUMA) architecture, private memory blocks are allocated within the explicit memory zone of a NUMA node for all CPUs designated to access that specific node. Under this scenario, if the system stubbornly adheres to the default minimum allocation unit to carve out memory for each individual CPU, it can introduce substantial memory waste. For instance, consider a scenario where 7 CPUs access a specific node, and each CPU requires 10 KiB of memory. If the minimum allocation unit evaluates to 4 KiB, each CPU demands 3 allocation units, leading to a total requirement of 21 allocation units across all 7 CPUs, which equates to 84 KiB of memory. Since the 7 CPUs only strictly require 70 KiB of payload memory, 14 KiB of memory is lost to fragmentation waste. Mathematically, allocating exactly 72 KiB of memory for the 7 CPUs is sufficient to satisfy the alignment constraint that the aggregate allocation must be an integer multiple of the allocation unit. Therefore, when allocating memory for each CPU corresponding to a NUMA node, dropping the operational allocation granularity down to 2 KiB allows the system to allocate exactly 72 KiB of memory across the 7 CPUs, thereby elevating memory utilization efficiency.

When Linux allocates private memory blocks for CPUs within a NUMA-based architecture, it establishes an optimal finalized allocation granularity, designated as Units Per Allocation (UPA), by continuously decrementing the allocation unit step-by-step. This algorithmic approach guarantees that the aggregate memory volume allocated to each individual NUMA node scales strictly as an integer multiple of the atomic minimum unit, while simultaneously maintaining peak memory utilization efficiency.

10.2.2 Private Memory Allocation Execution

For multi-core systems, the runtime operating states and executing tasks of each individual CPU may vary. Consequently, CPU-private variables (per_cpu variables) are required to preserve distinct variables to differentiate each processor from the others. Since private memory is restricted to a single CPU, under most circumstances, a CPU can access its own private variables without requiring locks. Linux provides the macro definition #define DEFINE_PER_CPU(type, name) DEFINE_PER_CPU_SECTION(type, name, "") to declare these CPU-private variables. Each CPU's private variables are stored within its own dedicated storage area, which is allocated via the function setup_per_cpu_areas(). For uniprocessor (UP) systems or symmetric multiprocessing (SMP) systems, this function is defined within the file git/mm/percpu.c. For NUMA systems, the function is defined inside git/arch/yourprocessorname/mm/numa.c (e.g., git/arch/arm64/mm/numa.c).

The function definition for uniprocessor (UP) systems is as follows:

void __init setup_per_cpu_areas(void)
{
	const size_t unit_size = roundup_pow_of_two(
		max_t(size_t, PCPU_MIN_UNIT_SIZE, PERCPU_DYNAMIC_RESERVE));
	struct pcpu_alloc_info *ai;
	void *fc;
	ai = pcpu_alloc_alloc_info(1, 1);
	fc = memblock_alloc_from(unit_size, PAGE_SIZE, __pa(MAX_DMA_ADDRESS));
	if (!ai || !fc)
		panic("Failed to allocate memory for percpu areas.");
	kmemleak_free(fc);
	ai->dyn_size = unit_size;
	ai->unit_size = unit_size;
	ai->atom_size = unit_size;
	ai->alloc_size = unit_size;
	ai->groups[0].nr_units = 1;
	ai->groups[0].cpu_map[0] = 0;
	pcpu_setup_first_chunk(ai, fc);
	pcpu_free_alloc_info(ai);
}

The function definition for symmetric multiprocessing (SMP) systems is as follows:

void __init setup_per_cpu_areas(void)
{
	unsigned long delta;
	unsigned int cpu;
	int rc;
	rc = pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE, PERCPU_DYNAMIC_RESERVE,PAGE_SIZE, NULL, pcpu_dfl_fc_alloc, pcpu_dfl_fc_free);
	if (rc < 0)
		panic("Failed to initialize percpu areas.");
	delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
	for_each_possible_cpu(cpu)
		__per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
}

ARM64 supports NUMA architectures, and its function definition is as follows:

void __init setup_per_cpu_areas(void)
{
	unsigned long delta;
	unsigned int cpu;
	int rc;
	rc = pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE, PERCPU_DYNAMIC_RESERVE, 
				  PAGE_SIZE, NULL, pcpu_dfl_fc_alloc, pcpu_dfl_fc_free);
	if (rc < 0)
		panic("Failed to initialize percpu areas.");
	delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
	for_each_possible_cpu(cpu)
		__per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
}

To facilitate memory management, Linux defines the structures struct pcpu_alloc_info and struct pcpu_group_info for the private memory allocation management subsystem. Among these, the pcpu_alloc_info structure preserves diverse metrics regarding memory sizes, memory grouping, and memory allocation granularities. It is defined as:

struct pcpu_alloc_info {
	size_t		static_size;
	size_t		reserved_size;
	size_t		dyn_size;
	size_t		unit_size;
	size_t		atom_size;
	size_t		alloc_size;
	size_t		__ai_size;
	int		nr_groups;
	struct pcpu_group_info	groups[];
}

Within this block, unit_size signifies the number of memory bytes allocated to a single CPU, and alloc_size represents the number of memory bytes actually allocated. The meanings of the remaining fields are clear and will not be individually described.

The structure struct pcpu_group_info is defined as:

struct pcpu_group_info {
	int			nr_units;
	unsigned long	base_offset;	
	unsigned int		*cpu_map;
};

It preserves the CPU grouping status, wherein nr_units represents the actual number of UPAs (Units Per Allocation) assigned to the corresponding node. base_offset stores the memory offset allocated for the node, where the offset of the first node evaluates to 0. cpu_map is an array that records the logical IDs of all CPUs associated with the current node.

With a basic understanding of private memory, the allocation process becomes easier to comprehend. For uniprocessor (UP) systems, the function setup_per_cpu_areas() first invokes the function pcpu_alloc_alloc_info(int nr_groups, int nr_units) to allocate memory for the structures pcpu_alloc_info and pcpu_group_info themselves, where nr_groups represents the number of NUMA nodes and nr_units represents the number of UPAs. Obviously, for a uniprocessor system, both nr_groups and nr_units equal 1.

After allocating memory for these two structures, setup_per_cpu_areas() directly calls the memblock memory allocator encountered previously to allocate sufficient CPU-private memory.

By comparing the setup_per_cpu_areas() function of symmetric multiprocessing (SMP) systems with that of NUMA systems, it can be observed that their function definitions are fundamentally identical. The only distinction lies in the final three parameters passed to the memory allocation function pcpu_embed_first_chunk(). An SMP system invokes it via pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE, PERCPU_DYNAMIC_RESERVE, PAGE_SIZE, NULL, pcpu_dfl_fc_alloc, pcpu_dfl_fc_free), whereas a NUMA system invokes it via pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE, PERCPU_DYNAMIC_RESERVE, PAGE_SIZE, pcpu_cpu_distance, pcpu_fc_alloc, pcpu_fc_free). The final three parameters of the pcpu_embed_first_chunk() function—cpu_distance_fn, alloc_fn, and free_fn—are callbacks utilized to determine the distance between each CPU and the different NUMA nodes, allocate memory, and free memory respectively. The memory allocation and deallocation functions resolve to the memblock allocation and deallocation routines (memblock_alloc_try_nid and memblock_free). Because all CPUs in an SMP system share an identical distance to the memory nodes—meaning there is only a single NUMA node—the distance determination callback passed to the pcpu_embed_first_chunk() function is specified as null.

An analysis of pcpu_embed_first_chunk() reveals that for SMP systems, its role is to invoke the function pcpu_build_alloc_info() to determine the number of units allocated per CPU (UPA—units per allocation), allocate memory for the structures pcpu_alloc_info and pcpu_group_info (by invoking the function pcpu_alloc_alloc_info()), perform initialization, and finally invoke the callback function alloc_fn() to allocate the private memory. When invoking pcpu_alloc_alloc_info(), nr_groups = 1, and nr_units represents the required number of units to be allocated (a multiple of UPA).

Aside from the memory allocation and deallocation functions, the callbacks passed to pcpu_embed_first_chunk() by a NUMA system include an additional function cpu_distance_fn(), which is utilized to determine the distance between a CPU and each memory node. pcpu_build_alloc_info() leverages this function to partition the CPUs into multiple groups (effectively grouping together the CPUs that access the exact same NUMA node).

pcpu_build_alloc_info() first determines the maximum value of UPA, then utilizes cpu_distance_fn() to group the CPU cores, and subsequently searches for an optimal UPA value. Following this, it allocates memory for the structures pcpu_alloc_info and pcpu_group_info via the function pcpu_alloc_alloc_info(), and finally initializes the two aforementioned structures.

After the function pcpu_build_alloc_info() returns, pcpu_embed_first_chunk() invokes the callback function alloc_fn() to sequentially allocate private memory for each group, and the allocated memory addresses are stored within the areas array. If the memory allocation callback function fails to execute successfully, the already allocated memory can be released via the callback function free_fn().

Following the allocation of private memory, if the hardware architecture is based on an SMP topology or a NUMA topology, the setup_per_cpu_areas() function must also initialize the contents of the __per_cpu_offset array to establish the precise locations of the per_cpu variables for each CPU within the private memory space.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com